package com.cust.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cust.sky.constant.MessageConstant;
import com.cust.sky.constant.StatusConstant;
import com.cust.sky.context.BaseContext;
import com.cust.sky.dto.DishDTO;
import com.cust.sky.dto.DishPageQueryDTO;
import com.cust.sky.entity.Dish;
import com.cust.sky.entity.DishFlavor;
import com.cust.sky.entity.Setmeal;
import com.cust.sky.entity.SetmealDish;
import com.cust.sky.exception.DeletionNotAllowedException;
import com.cust.sky.mapper.DishFlavorMapper;
import com.cust.sky.mapper.DishMapper;
import com.cust.sky.service.DishFlavorService;
import com.cust.sky.service.DishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cust.sky.service.SetmealDishService;
import com.cust.sky.service.SetmealService;
import com.cust.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品 服务实现类
 * </p>
 *
 * @author lei
 * @since 2024-07-10
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO, dish);
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());

        //向菜品表插入1条数据
        baseMapper.insert(dish);

        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(flavors)) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入n条数据
            dishFlavorService.saveBatch(flavors);
        }
    }

    /**
     * 条件分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public IPage getPage(DishPageQueryDTO dishPageQueryDTO) {
        int page = dishPageQueryDTO.getPage();
        int pageSize = dishPageQueryDTO.getPageSize();
        Integer categoryId = dishPageQueryDTO.getCategoryId();
        Integer status = dishPageQueryDTO.getStatus();
        String name = dishPageQueryDTO.getName();
        Page<DishVO> pageParam = new Page(page, pageSize);
        Page<DishVO> dishVOPage = baseMapper.pageQuery(pageParam, name, categoryId, status);
        return dishVOPage;
    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Transactional
    @Override
    public void removeDish(List<Long> ids) {
        //判断当前菜品是否能够删除---是否存在起售中的菜品？？
        for (Long id : ids) {
            Dish dish = baseMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //判断当前菜品是否能够删除---是否被套餐关联了？？
        List<Long> setmealIds = setmealDishService.getSetmealIdsByDishIds(ids);
        if (!CollectionUtils.isEmpty(setmealIds)) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品表中的菜品数据
        baseMapper.deleteBatchIds(ids);
        dishFlavorService.deleteByDishIds(ids);
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        DishVO dishVO = new DishVO();
        Dish dish = baseMapper.selectById(id);
        List<DishFlavor> dishFlavors = dishFlavorService.findByDishId(dish.getId());
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        baseMapper.updateById(dish);

        //删除原有的口味数据
        dishFlavorService.deleteByDishId(dishDTO.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(flavors)) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorService.saveBatch(flavors);
        }
    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = baseMapper.selectById(id);
        dish.setStatus(status);
        baseMapper.updateById(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
//            List<Long> dishIds = new ArrayList<>();
//            dishIds.add(id);
            List<Long> setmealIds = setmealDishService.getSetmealIdsByDishId(id);
            if (!CollectionUtils.isEmpty(setmealIds)) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = new Setmeal();
                    setmeal.setId(setmealId);
                    setmeal.setStatus(StatusConstant.DISABLE);
                    setmealService.updateById(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getDishByCategoryId(Long categoryId) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, categoryId);
        List<Dish> dishList = baseMapper.selectList(wrapper);
        return dishList;
    }

    /**
     * 根据分类id查询菜品及口味数据
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Long categoryId) {
        List<Dish> dishList = baseMapper.selectList(new LambdaQueryWrapper<Dish>()
                .eq(Dish::getCategoryId, categoryId)
                .eq(Dish::getStatus, StatusConstant.ENABLE));
        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish dish : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorService.findByDishId(dish.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 根据分类id查询菜品数量
     *
     * @param categoryId
     * @return
     */
    @Override
    public Integer countByCategoryId(Long categoryId) {
        Integer dishCount = baseMapper.selectCount(new LambdaQueryWrapper<Dish>()
                .eq(Dish::getCategoryId, categoryId));
        return dishCount;
    }

    /**
     * 根据套餐id查询菜品
     *
     * @param setmealId
     * @return
     */
    @Override
    public List<Dish> getBySetmealId(Long setmealId) {
        List<SetmealDish> setmealDishList = setmealDishService.getBySetmealId(setmealId);
        List<Long> dishIds = setmealDishList.stream()
                .map(item -> item.getDishId())
                .collect(Collectors.toList());
        List<Dish> dishList = baseMapper.selectBatchIds(dishIds);
        return dishList;
    }

}
